import { Group, RepeatWrapping, LineBasicMaterial, Vector3, SpriteMaterial, Sprite, Color, MeshStandardMaterial, DoubleSide,CylinderGeometry,Mesh,MeshBasicMaterial ,BoxGeometry,AdditiveBlending,PlaneGeometry,SRGBColorSpace} from "three"
import {  getBoundBox, emptyObject,GradientShader} from "@/mini3d"
import { ExtrudeMap } from "./extrudeMap"
import { geoMercator } from "d3-geo"
import { gsap } from "gsap"
export class ChildMap {
  constructor(parent, options) {
    this.baseScale = 7.182136710876198
    this.parent = parent
    this.instance = new Group()
    this.instance.rotateX(-Math.PI / 2)
    this.instance.position.set(0, 0.2, 0)
    this.first = localStorage.getItem("baseScale") || ""
    let defaultOptions = {
      adcode: 10000,
      center: [0, 0],
      centroid: [0, 0],
      childrenNum: 0,
      parentBoxSize: [1, 1], // 上级地图的尺寸
      mapData: {},
      geoProjectionCenter: [0, 0],
      geoProjectionScale: options.geoProjectionScale || 20,
      geoProjectionTranslate: [0, 0],
    }
    this.options = Object.assign({}, defaultOptions, options)
    this.labelGroup = new Group()
    // 保存圆柱体组
    this.barChartGroup = new Group();
    this.labelChildGroup = new Group()
    // 是否点击了
    this.clicked = false
    // 缩放值
    this.scale = 1
    // 地图的box大小
    this.boundBox = {}
    // 地图的区域数据
    this.areaData = []
    // 区域标签
    this.allAreaLabel = []
    // 区域标签组
    this.areaLabelGroup = new Group()
    // 区域点组
    this.areaPointGroup = new Group()
    // 信息标签组
    this.allInfoLabel = []
    this.infoLabelGroup = new Group()
    this.instance.add(this.areaLabelGroup)
    // 事件元素
    this.eventElement = []
    this.pointEventElement = []
    this.init()
  }
  init() {
    this.createModel()
    this.addLabel()
    // 创建圆柱
    this.createBarCharts(); 
    if (this.options.childrenNum) {
      this.addEvent()
    }
    this.addPointEvent()
  }
  createModel() {
    let { map } = this.createMap()
    // this.setScale(map)
    map.setParent(this.instance)
    
    
  }
  createQuan(position, index) {
    const guangquan1 = this.parent.assets.instance.getResource("guangquan1");
    const guangquan2 = this.parent.assets.instance.getResource("guangquan2");
    if (!guangquan1 || !guangquan2) {
        console.error("光圈纹理加载失败!");
        return new Group(); // 返回空组避免报错
    }
    console.log(position)
    let geometry = new PlaneGeometry(0.5, 0.5);
    let material1 = new MeshBasicMaterial({
      color: 0xffffff,
      map: guangquan1,
      alphaMap: guangquan1,
      opacity: 1,
      transparent: true,
      depthTest: false,
      fog: false,
      blending: AdditiveBlending,
      depthWrite:false
    });
    let material2 = new MeshBasicMaterial({
      color: 0xffffff,
      map: guangquan2,
      alphaMap: guangquan2,
      opacity: 1,
      transparent: true,
      depthTest: false,
      fog: false,
      blending: AdditiveBlending,
      depthWrite:false
    });
    let mesh1 = new Mesh(geometry, material1);
    let mesh2 = new Mesh(geometry, material2);
    
    mesh1.renderOrder = 6;
    mesh2.renderOrder = 6;
    mesh1.rotateX(Math.PI / 2);
    mesh2.rotateX(Math.PI / 2);
    mesh1.position.copy(position);
    mesh2.position.copy(position);
    // mesh2.position.y -= 0.001;
    mesh1.scale.set(1, 1, 1);
    mesh2.scale.set(1, 1, 1);
    this.quanGroup = new Group();
    this.quanGroup.add(mesh1, mesh2);
    return this.quanGroup;
  }
  // 在ChildMap类中添加创建圆柱图的方法
  createBarCharts() {
    this.allGuangquan = [];

    let data = this.areaData.map((item,index)=>{
      item.count =  Math.floor(Math.random() * 1000) + 1;
      return item
    })
    // 创建圆柱图组
    this.barChartGroup = new Group();
    
    const factor = 2 / this.scale
    const baseDepth = (this.parent.depth + 5)/this.scale
    // 存储所有圆柱图和标签
    this.allBars = [];
    this.allBarLabels = [];
    
    // 圆柱图参数
    
    const radius = 0.2 * factor; // 圆柱半径
    const max = 100
    const maxCount = Math.max(...data.map(item => item.count));
    const height = 5.0 * factor
    const colors = [0x2CE2FE, 0x50bbfe, 0x77fbf5, 0xfbdf88, 0xfffef4]; // 颜色数组
    
    // 遍历区域数据创建圆柱图
    data.forEach((item, index) => {
      // 随机生成高度（实际项目中应根据数据确定）
      // const height = minHeight + Math.random() * (maxHeight - minHeight);
      let geoHeight = height * (((item.count*100) / maxCount) / max)
      // 2. 创建材质
      const colorIndex = index % colors.length;
      let material = new MeshBasicMaterial({
        color: 0xfbdf88,
        transparent: true,
        opacity: 1,
        // depthTest: false,
        // fog: false,
        roughness: 0.2,
        // // emissive: new Color(colors[colorIndex]).multiplyScalar(0.2),
        emissiveIntensity: 0.5
      })
      new GradientShader(material, {
        uColor1: "0xfbdf88",
        uColor2: "0x77fbf5",
        size: geoHeight,
        dir: "y",
      })
      
      // 创建圆柱几何体
      const geometry = new CylinderGeometry(radius, radius, geoHeight, 32);
      geometry.translate(0, geoHeight / 2, 0); // 将圆柱底部放在原点
      
      //  创建圆柱网格
      const cylinder = new Mesh(geometry, material);
      cylinder.rotation.x = Math.PI / 2; // 旋转使圆柱竖立
      // 设置位置
      const [x, y] = this.geoProjection(item.centroid);
      cylinder.position.set(x, -y,  baseDepth);
      // cylinder.scale.set(1, 1, 0); // 初始缩放为0，用于动画
      
      // 5. 添加用户数据
      cylinder.userData = {
        type: "bar",
        areaData: item,
        height: geoHeight,
        index: index,
        adcode: item.adcode // 添加adcode用于匹配
      };
      const worldPos = new Vector3(0, -baseDepth+2, baseDepth+0.05);
       // 创建光圈 - 先设置世界坐标
      let guangQuan = this.createQuan(
        worldPos,
        index
      );
      cylinder.add(guangQuan)
      
       // 调试信息 - 获取世界坐标
        console.log(`光圈 ${index} 世界坐标:`, guangQuan.getWorldPosition(new Vector3()));

      
      // this.allGuangquan.push(guangQuan);
      // 6. 添加到组
      console.log("xxx光圈=============")
      console.log(guangQuan)
      
      this.barChartGroup.add(cylinder);
      this.allBars.push(cylinder);
      
      const labelPosition = new Vector3(
        x, 
        -y, 
       ((this.parent.depth + geoHeight + 0.5)/ this.scale * this.baseScale)
      );
      
      const label = this.createBarLabel(item, item.count, labelPosition, colorIndex);
      const baseScale = localStorage.getItem("baseScale")
      console.log("当前缩放比=====")
      console.log(this.scale)
      console.log("基准缩放比")
      console.log(baseScale)
      if(!this.first){
        localStorage.setItem("baseScale",this.scale)
      }
      this.allBarLabels.push(label);
      

      // 在 createBarCharts 方法末尾添加
    

    });
    this.instance.add(this.barChartGroup);

    // 8. 设置缩放和位置
    this.setBarScale();
    
    // 9. 播放动画
    this.animateBars();

    // 添加光圈动画
    // this.animateQuan();


    // console.log("光圈数量:", this.allGuangquan.length);
    // console.log(this.allGuangquan)
    // console.log("第一个光圈的位置:", this.allGuangquan[0]?.position);
    // console.log("第一个光圈的子对象:", this.allGuangquan[0]?.children);
  }
  // 添加光圈动画方法
  animateQuan() {
    this.allGuangquan.forEach((quanGroup, index) => {
      // 第一个光圈的动画
      const mesh1 = quanGroup.children[0];
      const mesh2 = quanGroup.children[1];
      
      gsap.to(mesh1.scale, {
        x: 1.5,
        y: 1.5,
        duration: 1.5,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay: index * 0.2
      });
      
      gsap.to(mesh2.scale, {
        x: 1.8,
        y: 1.8,
        duration: 2,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay: index * 0.2
      });
      
      // 透明度动画
      gsap.to(mesh1.material, {
        opacity: 0.7,
        duration: 1.5,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay: index * 0.2
      });
      
      gsap.to(mesh2.material, {
        opacity: 0.5,
        duration: 2,
        repeat: -1,
        yoyo: true,
        ease: "sine.inOut",
        delay: index * 0.2
      });
    });
  }

  // 创建圆柱图数值标签
  createBarLabel(data, value, position, colorIndex) {
    const label3d = this.parent.label3d;
    const label = label3d.create("", "bar-value-label", true);
    
    const colorClass = "yellow" ;
    
    label.init(
      `<div class="bar-value-label ${colorClass}">
        <div class="bar-value-label-wrap">
          <span class="value">${value}</span>
          <span class="unit">个</span>
        </div>
      </div>`,
      position
    );
    
    label3d.setLabelStyle(label, 0.05 / this.scale, "x");
    label.setParent(this.barChartGroup);
    label.userData.isBillboard = true;
    label.userData.barData = data;
    label.userData.value = value

    
    
    // 初始隐藏，动画显示
    label.element.querySelector(".bar-value-label-wrap").style.opacity = 0;
    label.element.querySelector(".bar-value-label-wrap").style.transform = "translateY(20px)";
    
    return label;
  }

  // 设置圆柱图组的缩放
  setBarScale() {
    this.barChartGroup.scale.set(this.scale, this.scale, this.scale);
    this.barChartGroup.position.x = -this.boundBox.center.x;
    this.barChartGroup.position.y = -this.boundBox.center.y;


    
    // 更新标签位置
    this.allBarLabels.forEach((label, index) => {
      const bar = this.allBars[index];
      const height = bar.userData.height;
      // 使用与 setBarScale 相同的计算方式
      const geoHeight = this.getGeoheight(label.userData.value);
      // label.position.z = (this.parent.depth/this.scale + 10/this.scale ) + (geoHeight/this.scale+ 5/this.scale) + 2/this.scale;

      label.position.z =  geoHeight + ((this.parent.depth+0.5) / this.scale * this.baseScale);

      // label.position.z = (this.parent.depth + height + 4 / this.scale) ;
      label.scale.set(0.1 / this.scale, 0.1 / this.scale, 0.1 / this.scale);
    });
  }

  // 圆柱图动画
  animateBars() {
    const tl = gsap.timeline();
    
    // 圆柱生长动画
    this.allBars.forEach((bar, index) => {
      tl.to(bar.scale, {
        z: 1,
        duration: 0.8,
        delay: index * 0.05,
        ease: "back.out"
      }, "start");
    });
    
    // 标签显示动画
    this.allBarLabels.forEach((label, index) => {
      const element = label.element.querySelector(".bar-value-label-wrap");
      tl.to(element, {
        opacity: 1,
        y: 0,
        duration: 0.5,
        delay: index * 0.05 + 0.3,
        ease: "power2.out"
      }, "start");
    });
  }

  // 创建省份
  createMap() {
    let mapJsonData = this.options.mapData
    let topNormal = this.parent.assets.instance.getResource("topNormal")
    topNormal.wrapS = topNormal.wrapT = RepeatWrapping

    this.mapLineMaterial = new LineBasicMaterial({
      color: 0x2CE2FE,
      opacity: 0,
      transparent: true,
      fog: false,
    })
    let [top, side] = this.parent.createProvinceMaterial()
    let topMaterial = top.clone()
    topMaterial.opacity = 1
    let sideMaterial = side.clone()
    sideMaterial.opacity = 1
    let faceMaterial = new MeshStandardMaterial({
      emissive: new Color(0x1364a8),
      emissiveIntensity: 2,
      transparent: true,
      opacity: 0.7,
      side: DoubleSide // 确保双面可见
    })
    faceMaterial.userData = {
      isSelected: false,
      originalPosition: null
    };

    // 直接修改材质着色器（确保在 GradientShader 之后）
    faceMaterial.onBeforeCompile = (shader) => {
      // 顶点着色器传递 uv
      shader.vertexShader = shader.vertexShader.replace(
        'void main() {',
        `
        varying vec2 vUv;
        void main() {
          vUv = uv;
        `
      );
    
      // 片元着色器添加 uniform 和 varying，放在全局声明区
      shader.fragmentShader = shader.fragmentShader.replace(
        'void main() {',
        `
        varying vec2 vUv;
        uniform vec3 uGlowColor;
        uniform float uGlowIntensity;
        uniform float uGlowRadius;
        uniform vec3 uColor1;
        uniform vec3 uColor2;
        void main() {
        `
      );
    }
      this.defaultMaterial = faceMaterial
      this.defaultLightMaterial = this.defaultMaterial.clone()
      this.defaultLightMaterial.color = new Color("#1364a8")
      this.defaultLightMaterial.opacity = 1
      this.defaultLightMaterial.emissive.setHex(new Color("#1364a8"));
      this.defaultLightMaterial.emissiveIntensity = 3.5;
  
    let map = new ExtrudeMap(this.parent, {
      geoProjectionScale:this.options.geoProjectionScale || this.geoProjectionScale,
      scale:this.scale,
      center: this.options.center,
      position: new Vector3(0, 0, 0.06 * this.scale / this.baseScale),
      data: mapJsonData,
      depth: this.parent.depth+5,
      topFaceMaterial: this.defaultLightMaterial,
      sideMaterial: sideMaterial,
      lineMaterial: this.parent.mapLineMaterial,
      renderOrder: 9,
    })
    this.areaData = map.coordinates
    let { boxSize, box3 } = getBoundBox(map.mapGroup)
    map.mapGroup.children.map((group, index) => {
      group.children.map((mesh) => {
        if (mesh.type === "Mesh") {
          mesh.userData.type = "map"
          this.eventElement.push(mesh)
          this.parent.calcUv2(mesh.geometry, boxSize.x, boxSize.y, box3.min.x, box3.min.y)
        }
      })
    })
    this.setScale(map);
    return {
      map,
    }
  }

  getGeoheight(count){
    const factor = 2 / this.scale
    const height = 5.0 * factor
    const max = 100
    const maxCount = Math.max(...this.areaData.map(item => item.count));
    return  height * (((count*100) / maxCount) / max)
  }
  addEvent() {
    let objectsHover = []
    const baseDepth = (this.parent.depth + 5)/this.scale
    


    const reset = (mesh) => {
      gsap.to(mesh.scale, {
        duration: 0.3,
        z: 1,
        onComplete: () => {
          mesh.traverse((obj) => {
            if (obj.isMesh) {
              obj.material[0].emissive.setHex(mesh.userData.materialEmissiveHex)
              obj.material[0].emissiveIntensity = 1
              obj.renderOrder = 9
            }
          })
        },
      })
      // 恢复柱形图状态
      console.log("reset this.parent.depth + 0.1")
      console.log(this.parent.depth + 0.1)

      // 复位标签
      this.allBarLabels.forEach(label => {
        if (label.userData.barData.adcode === mesh.userData.adcode) {
          const geoHeight = this.getGeoheight(label.userData.barData.count)
          gsap.to(label.position, {
            duration: 0.3,
            z: geoHeight + ((this.parent.depth +0.5)/this.scale * this.baseScale), // 恢复到原始位置
            ease: "power2.out"
          });
        }
      });
      // 恢复对应的圆柱图位置
      this.allBars.forEach(bar => {
        if (bar.userData.areaData.adcode === mesh.userData.adcode) {
          gsap.to(bar.position, {
            duration: 0.3,
            z: baseDepth,
            ease: "power2.out"
          });
        }
      });


      
      this.setLabelMove(mesh.userData.adcode, "down")
      this.setPointMove(mesh.userData.adcode, "down")
    }
    const move = (mesh) => {
      gsap.to(mesh.scale, {
        duration: 0.3,
        z: 1.5,
      })
      console.log("move this.parent.depth + 0.1")
      console.log(this.parent.depth + 0.5)
      this.allBars.forEach(bar => {
      if (bar.userData.areaData.adcode === mesh.userData.adcode) {
          gsap.to(bar.position, {
            duration: 0.3,
            z: baseDepth+(5/this.scale), // 与地图凸起高度匹配
            ease: "power2.out"
          });
        }
      });


      // 移动对应的标签
      this.allBarLabels.forEach(label => {
        if (label.userData.barData.adcode === mesh.userData.adcode) {
          console.log(label.userData.barData)
          console.log(mesh.userData)
          const geoHeight = this.getGeoheight(label.userData.barData.count)

      // label.position.z = (this.parent.depth + geoHeight + 4 / this.scale) / this.scale;
          gsap.to(label.position, {
            duration: 0.3,
            z:geoHeight+ ((this.parent.depth + 1.5)/this.scale * this.baseScale) , // 向上移动相同的距离
            ease: "power2.out"
          });
        }
      });
      this.setLabelMove(mesh.userData.adcode)
      this.setPointMove(mesh.userData.adcode)
      mesh.traverse((obj) => {
        if (obj.isMesh) {
          obj.material[0].emissive.setHex(0x0b112d)
          obj.material[0].emissiveIntensity = 1.5
          obj.renderOrder = 21
        }
      })
    }

    // 循环添加事件
    this.eventElement.map((mesh) => {
      this.parent.interactionManager.add(mesh)
      mesh.addEventListener("mousedown", (event) => {
        if (this.clicked) return false
        this.clicked = true
        let userData = event.target.parent.userData
        this.parent.history.push(userData)
        this.parent.loadChildMap(userData.name)
      })
      mesh.addEventListener("mouseup", (ev) => {
        this.clicked = false
      })
      mesh.addEventListener("mouseover", (event) => {
        if (!objectsHover.includes(event.target.parent)) {
          objectsHover.push(event.target.parent)
        }

        document.body.style.cursor = "pointer"
        move(event.target.parent)
      })
      mesh.addEventListener("mouseout", (event) => {
        objectsHover = objectsHover.filter((n) => n.userData.name !== event.target.parent.userData.name)
        if (objectsHover.length > 0) {
          const mesh = objectsHover[objectsHover.length - 1]
        }
        reset(event.target.parent)
        document.body.style.cursor = "default"
      })
    })
    this.allBars.forEach(bar => {
      this.parent.interactionManager.add(bar);
      bar.addEventListener("mouseover", () => {
        const mapMesh = this.eventElement.find(m => 
          m.parent.userData.adcode === bar.userData.areaData.adcode
        );
        if (mapMesh) {
          move(mapMesh.parent);
        }
      });
      
      bar.addEventListener("mouseout", () => {
        const mapMesh = this.eventElement.find(m => 
          m.parent.userData.adcode === bar.userData.areaData.adcode
        );
        if (mapMesh) {
          reset(mapMesh.parent);
        }
      });
    });
  }
  // 添加标点事件
  addPointEvent() {
    let objectsHover = []

    this.pointEventElement.map((mesh) => {
      this.parent.interactionManager.add(mesh)
      mesh.addEventListener("mousedown", (event) => {
        if (this.clicked) return false
        this.clicked = true
        let userData = event.target.userData
        this.allInfoLabel.map((label, index) => {
          label.hide()
          if (userData.index === index) {
            label.show()
          }
        })
      })
      mesh.addEventListener("mouseup", (ev) => {
        this.clicked = false
      })
      mesh.addEventListener("mouseover", (event) => {
        if (!objectsHover.includes(event.target.parent)) {
          objectsHover.push(event.target.parent)
        }

        document.body.style.cursor = "pointer"
        let sprite = event.target
        sprite.material = this.pointHoverMaterial.clone()
      })
      mesh.addEventListener("mouseout", (event) => {
        objectsHover = objectsHover.filter((n) => n.userData.name !== event.target.parent.userData.name)
        if (objectsHover.length > 0) {
          const mesh = objectsHover[objectsHover.length - 1]
        }

        document.body.style.cursor = "default"
        let sprite = event.target
        sprite.material = this.pointDefaultMaterial.clone()
      })
    })
  }
  // 设置标签移动
  setLabelMove(adcode, type = "up") {
    [...this.allAreaLabel].map((label) => {
      if (label.userData.adcode === adcode) {
        gsap.to(label.position, {
          duration: 0.3,
          z: type === "up" ? label.userData.position[2] + 3 / this.scale : label.userData.position[2],
        })
      }
    })
  }
  // 设置点移动
  setPointMove(adcode, type = "up") {
    this.areaPointGroup.children.map((point) => {
      if (point.userData.adcode === adcode) {
        gsap.to(point.position, {
          duration: 0.3,
          z: type === "up" ? point.userData.position[2] + 3 / this.scale : point.userData.position[2],
        })
      }
    })
  }
  addLabel() {
    // 贴图
    const texture = this.parent.assets.instance.getResource("point")

    const material = new SpriteMaterial({
      map: texture,
      color: 0xffffff,
      transparent: true,
      depthTest: false,
    })
    this.pointDefaultMaterial = material
    this.pointHoverMaterial = material.clone()
    this.pointHoverMaterial.color = new Color(0x2CE2FE)
    const sprite = new Sprite(material)
    sprite.renderOrder = 23
    this.areaData.map((item, index) => {
      
      let [x, y] = this.geoProjection(item.centroid)
      // 名称
      let nameLabel = this.labelNameStyle(item, index, new Vector3(x, -y, 0))
      this.allAreaLabel.push(nameLabel)
      // 信息
      let infoLabel = this.infoLabel(item, index, new Vector3(x, -y, 0))
      this.allInfoLabel.push(infoLabel)

      //点
      let areaPoint = sprite.clone()
      sprite.material = material.clone()
      areaPoint.position.set(x, -y, 0)
      areaPoint.userData.adcode = item.adcode

      areaPoint.userData.type = "point"
      areaPoint.userData.name = item.name
      areaPoint.userData.position = [x, -y, 0]
      areaPoint.userData.index = index
      this.areaPointGroup.add(areaPoint)
    })
    this.setNameScale()
    this.setInfoScale()
    this.setPointScale()
  }
  infoLabel(data, index, position) {
    let label3d = this.parent.label3d
    let label = label3d.create("", "info-point", true)

    label.init(
      ` <div class="info-point-wrap">
      <div class="info-point-wrap-inner">
        <div class="info-point-line">
          <div class="line"></div>
          <div class="line"></div>
          <div class="line"></div>
        </div>
        <div class="info-point-content">
          <div class="content-item"><span class="label">名称</span><span class="value">${data.name}</span></div>
          <div class="content-item"><span class="label">PM2.5</span><span class="value">100ug/m²</span></div>
          <div class="content-item"><span class="label">等级</span><span class="value">良好</span></div>
        </div>
      </div>
    </div>
  `,
      position
    )
    label3d.setLabelStyle(label, 0.06 / this.scale, "x")
    label.setParent(this.infoLabelGroup)
    // label.hide()
    return label
  }

  
  // 城市标签
  labelNameStyle(data, index, position) {

    // position.x = position.x * 120
    // position.y = position.y * 120
    let label3d = this.parent.label3d
    let label = label3d.create("", "area-name-label", true)
    label.init(`<div class="area-name-label-wrap">${data.name}</div>`, position)
    console.log("城市==========")
    console.log(this.baseScale)
    console.log(this.scale)
    label3d.setLabelStyle(label, 0.1 / this.scale, "x")
    label.setParent(this.areaLabelGroup)
    label.userData.adcode = data.adcode
    label.userData.position = [position.x, position.y, position.z]
    return label

  }

  calculateScale(parentBoxSize, boxSize) {
    let xScale = parentBoxSize[0] / boxSize[0]
    let yScale = parentBoxSize[1] / boxSize[1]
    let scale = Math.min(xScale, yScale)

    return scale
  }

  setScale(map) {
    let { parentBoxSize } = this.options
    let boundBox = getBoundBox(map.mapGroup)

    let scale = this.calculateScale(parentBoxSize, [boundBox.boxSize.x, boundBox.boxSize.y])

    // modify by LING: 切换四级地图后文字偏小
    if(map.coordinates.length < 2) {
      scale = scale / 2; // 调整这个scale值，使最小层级的地图文字都放大一些
    } else {
      scale = scale / 1.4;
    }
    
    // 子地图缩放到主地图大小
    map.mapGroup.scale.set(scale, scale, 1)
    let boundBox1 = getBoundBox(map.mapGroup)
    // 放大后，中心坐标有偏移，偏移了多少，就反向移动多少
    map.mapGroup.position.x = -boundBox1.center.x
    map.mapGroup.position.y = -boundBox1.center.y
    this.scale = scale
    this.boundBox = boundBox1
  }

  //设置城市标签缩放比
  setNameScale() {
    this.areaLabelGroup.scale.set(this.scale, this.scale, this.scale)
    this.areaLabelGroup.position.x = -this.boundBox.center.x
    this.areaLabelGroup.position.y = -this.boundBox.center.y
    this.allAreaLabel.map((label) => {
      let z = (this.parent.depth * 10 + 0.4) / this.scale
      
      label.position.z = z 
      console.log(z)

      label.position.y -= 1.5 / this.scale
      label.userData.position = [label.position.x, label.position.y, label.position.z]
    })

    
  }

  setPointScale() {
    this.areaPointGroup.scale.set(this.scale, this.scale, this.scale)

    this.areaPointGroup.position.x = -this.boundBox.center.x
    this.areaPointGroup.position.y = -this.boundBox.center.y
    this.areaPointGroup.children.map((point) => {
      let z = (this.parent.depth + 1.4) / this.scale
      point.position.z = z
      point.userData.position[2] = z

      point.scale.set(5 / this.scale, 5 / this.scale, 5 / this.scale)

      point.userData.position = [point.position.x, point.position.y, point.position.z]

      this.pointEventElement.push(point)
    })
  }

  setInfoScale() {
    this.infoLabelGroup.scale.set(this.scale, this.scale, this.scale)

    this.infoLabelGroup.position.x = -this.boundBox.center.x
    this.infoLabelGroup.position.y = -this.boundBox.center.y
    this.infoLabelGroup.children.map((point) => {
      let z = (this.parent.depth + 10) / this.scale
      point.position.z = z

      point.scale.set(0.06 / this.scale, 0.06 / this.scale, 0.06 / this.scale)
    })
  }
  geoProjection = (args) => {
    let { geoProjectionScale, geoProjectionTranslate, center } = this.options
    return geoMercator().center(center).scale(120).translate(geoProjectionTranslate)(args)
  }

  setParent(parent) {
    parent.add(this.instance)
  }

  destroy() {
    console.log("触发清除事件-------------")
    ;[...this.allAreaLabel, ...this.allInfoLabel,...this.allBarLabels].map((label) => {
      label.remove()
    })
    this.removeElement(".area-name-label")
    this.removeElement(".info-point")
    ;[...this.eventElement, ...this.pointEventElement].map((mesh) => {
      this.parent.interactionManager.remove(mesh)
    })
    // 清除圆柱图组
    if (this.barChartGroup) {
      // 清除圆柱图网格
      this.allBars.forEach(bar => {
        if (bar.geometry) bar.geometry.dispose()
        if (bar.material) {
          // 如果是数组则遍历处理
          if (Array.isArray(bar.material)) {
            bar.material.forEach(mat => mat.dispose())
          } else {
            bar.material.dispose()
          }
        }
        this.barChartGroup.remove(bar)
      })
      
      // 清除圆柱图组
      emptyObject(this.barChartGroup)
      this.instance.remove(this.barChartGroup)
      
      // 重置相关属性
      this.allBars = []
      this.allBarLabels = []
    }
    
    emptyObject(this.instance)
    // 重置其他状态
    this.clicked = false
    this.scale = 1
    this.boundBox = {}
    this.areaData = []
    this.allAreaLabel = []
    this.allInfoLabel = []
    this.eventElement = []
    this.pointEventElement = []

    
  }
  removeElement(elementClassName) {
    var elements = document.querySelectorAll(elementClassName)
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i]
      const parent = element.parentNode
      parent.removeChild(element)
    }
  }
}
